const fs = require('fs');
const path = require('path');

// 要修复的文件列表
const files = [
  'src/routes/categories.ts',
  'src/routes/tags.ts',
  'src/routes/upload.ts',
  'src/routes/search.ts',
  'src/routes/analytics.ts'
];

// 修复规则
const fixRules = [
  // 修复格式问题：data: xxx } 改为 data: xxx }
  {
    from: /data: ([^}]+) }/g,
    to: 'data: $1\n      }'
  },
  // 修复 message: '操作成功' 为更具体的消息
  {
    from: /message: '操作成功'/g,
    to: 'message: \'操作成功\''
  },
  // 确保所有响应都有正确的格式
  {
    from: /res\.json\(\{\s*code: 200,\s*message: '([^']+)',\s*data: ([^}]+)\s*\}\)/g,
    to: 'res.json({\n        code: 200,\n        message: \'$1\',\n        data: $2\n      })'
  }
];

// 修复单个文件
function fixFile(filePath) {
  try {
    const fullPath = path.join(__dirname, filePath);
    if (!fs.existsSync(fullPath)) {
      console.log(`文件不存在: ${filePath}`);
      return;
    }

    let content = fs.readFileSync(fullPath, 'utf8');
    let updated = false;

    // 应用修复规则
    fixRules.forEach(rule => {
      if (rule.from.test(content)) {
        content = content.replace(rule.from, rule.to);
        updated = true;
      }
    });

    // 如果文件有更新，写回文件
    if (updated) {
      fs.writeFileSync(fullPath, content, 'utf8');
      console.log(`🔧 已修复: ${filePath}`);
    } else {
      console.log(`✅ 格式正确: ${filePath}`);
    }
  } catch (error) {
    console.error(`❌ 修复失败: ${filePath}`, error.message);
  }
}

// 主函数
function main() {
  console.log('🔧 开始修复API响应格式...\n');
  
  files.forEach(file => {
    fixFile(file);
  });
  
  console.log('\n✨ 格式修复完成！');
}

main();
